package com.fruitshop.manager;

import com.fruitshop.manager.base.BaseManager;
import com.fruitshop.mapper.FruitMapper;
import com.fruitshop.mapper.BuyRecordMapper;
import com.fruitshop.model.BuyRecord;
import com.fruitshop.model.Command;
import com.fruitshop.model.Fruit;
import com.fruitshop.model.User;
import com.fruitshop.util.ConsoleUtils;
import com.fruitshop.util.DBUtil;
import com.fruitshop.util.PrintUtils;
import com.fruitshop.util.UserInfoContext;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;

public class FruitManager extends BaseManager {


    // 水果列表
    private static final String LIST="1";

    // 添加水果
    private static final String ADD="2";

    // 删除水果
    private static final String DELETE="3";

    // 修改水果
    private static final String UPDATE="4";

    // 购买水果
    private static final String USER_BUY="5";

    public FruitManager(String title, List<Command> commandList) {
        super(title, commandList);
    }

    @Override
    protected String processCommand(String command) {
        switch (command) {
            case LIST:
                return showList();
            case ADD:
                return showAdd();
            case DELETE:
                return showDelete();
            case UPDATE:
                return showUpdate();
            case USER_BUY:
                return showUserBuy();

        }
        return command;
    }

    private String showUserBuy() {
        showFruitList();
        User user = UserInfoContext.getUser();

        //输入购买的水果id
        int id = ConsoleUtils.readInt(new Scanner(System.in), "请输入要购买的水果id");
        //输入购买的水果数量
        int amount = ConsoleUtils.readInt(new Scanner(System.in), "请输入要购买的水果数量");
        FruitMapper fruitMapper = DBUtil.getMapper(FruitMapper.class);
        Fruit fruit = fruitMapper.selectByPrimaryKey(id);
        if (fruit == null) {
            PrintUtils.printError("不存在该水果");
            ConsoleUtils.prompt(new Scanner(System.in), "任意按键退出");
            return NORMAL_EXIT;
        }
        if (fruit.getAmount() < amount) {
            PrintUtils.printError("库存不足");
            ConsoleUtils.prompt(new Scanner(System.in), "任意按键退出");
            return NORMAL_EXIT;
        }
        fruit.setAmount(fruit.getAmount() - amount);

        fruitMapper.updateByPrimaryKeySelective(fruit);

        // 生成购买记录

        BuyRecordMapper buyRecordMapper = DBUtil.getMapper(BuyRecordMapper.class);


        BuyRecord buyRecord = new BuyRecord();
        buyRecord.setAmount(amount);
        buyRecord.setFruitId(id);
        buyRecord.setAmount(amount);
        buyRecord.setPrice(fruit.getPrice().multiply(new BigDecimal(amount)));
        buyRecord.setUserId(user.getId());
        buyRecord.setBuyTime(LocalDateTime.now());
        buyRecordMapper.insert(buyRecord);

        PrintUtils.println("购买成功");
        ConsoleUtils.prompt(new Scanner(System.in), "任意按键退出");
        return NORMAL_EXIT;
    }

    private String showUpdate() {
        showFruitList();
        int id = ConsoleUtils.readInt(new Scanner(System.in), "请输入要修改的水果id");
        FruitMapper fruitMapper = DBUtil.getMapper(FruitMapper.class);
        Fruit fruit = fruitMapper.selectByPrimaryKey(id);
        if (fruit == null) {
            PrintUtils.printError("不存在该水果");
            ConsoleUtils.prompt(new Scanner(System.in), "任意按键退出");
            return NORMAL_EXIT;
        }
        Scanner scanner = new Scanner(System.in);
        String name = ConsoleUtils.readStringDefault(scanner, String.format("请输入水果名称,默认值为：%s", fruit.getName()), fruit.getName());
        int amount = ConsoleUtils.readIntDefault(scanner, "请输入水果数量,大于0，默认值为："+fruit.getAmount(), fruit.getAmount(),value -> value>0);
        BigDecimal price = ConsoleUtils.readDecimalDefault(scanner, "请输入水果单价,大于0,默认值为："+fruit.getPrice(), fruit.getPrice(),value -> value.compareTo(BigDecimal.ZERO)> 0);
        fruit.setName(name);
        fruit.setAmount(amount);
        fruit.setPrice(price);
        Fruit byName = fruitMapper.selectByName(name);

        if (byName != null && !byName.getId().equals(id)) {
            PrintUtils.printError("已存在相同名称的水果");
            ConsoleUtils.prompt(scanner, "任意按键退出");
            return NORMAL_EXIT;
        }
        fruitMapper.updateByPrimaryKeySelective(fruit);
        PrintUtils.println("修改成功");
        ConsoleUtils.prompt(scanner, "任意按键退出");
        return NORMAL_EXIT;
    }

    private String showDelete() {
        showFruitList();
        int id = ConsoleUtils.readInt(new Scanner(System.in), "请输入要删除的水果id");
        FruitMapper fruitMapper = DBUtil.getMapper(FruitMapper.class);
        Fruit fruit = fruitMapper.selectByPrimaryKey(id);
        if (fruit == null) {
            PrintUtils.printError("不存在该水果");
            ConsoleUtils.prompt(new Scanner(System.in), "任意按键退出");
            return NORMAL_EXIT;
        }

        fruitMapper.deleteByPrimaryKey(id);

        PrintUtils.println("删除成功");
        ConsoleUtils.prompt(new Scanner(System.in), "任意按键退出");

        return NORMAL_EXIT;
    }

    private String showAdd() {
        Scanner scanner = new Scanner(System.in);
        String name = ConsoleUtils.readString(scanner, "请输入水果名称");
        int amount = ConsoleUtils.readInt(scanner, "请输入水果数量,大于0", value -> value>0);
        BigDecimal price = ConsoleUtils.readDecimal(scanner, "请输入水果单价,大于0", value -> value.compareTo(BigDecimal.ZERO)>0);

        Fruit fruit = new Fruit();
        fruit.setName(name);
        fruit.setAmount(amount);
        fruit.setPrice(price);
        FruitMapper mapper = DBUtil.getMapper(FruitMapper.class);
        Fruit byName = mapper.selectByName(fruit.getName());

        if (byName != null) {
            PrintUtils.printError("已存在相同名称的水果");
            ConsoleUtils.prompt(scanner, "任意按键退出");
            return NORMAL_EXIT;
        }

        mapper.insert(fruit);
        PrintUtils.println("添加成功");
        ConsoleUtils.prompt(scanner, "任意按键退出");
        return NORMAL_EXIT;
    }

    private void showFruitList(){
        FruitMapper mapper = DBUtil.getMapper(FruitMapper.class);
        List<Fruit> fruits = mapper.selectAll();
        PrintUtils.printHighLight("水果id\t\t水果名称\t\t水果数量\t\t水果单价（元）");
        fruits.forEach(fruit -> {
            PrintUtils.println(fruit.getId() + "\t\t" + fruit.getName() + "\t\t" + fruit.getAmount() + "\t\t" + fruit.getPrice());
        });
    }
    private String showList() {
        showFruitList();
        Scanner scanner = new Scanner(System.in);
        ConsoleUtils.prompt(scanner,"任意按键退出" );
        return NORMAL_EXIT;
    }
}
